#!/usr/bin/python

import logging
logging.basicConfig(filename = "/home/g5tf87/bingPhoto.log",level = logging.DEBUG, format = '%(asctime)s - %(levelname)s: %(message)s')
logging.info("start script")
import urllib,re,os,time
import urllib2
picLocation="/media/4Download/Download/wallpaperChanged/"

for fd in os.listdir(picLocation):
    now=time.asctime().split()
    now[3]=now[0]+now[1]+now[2]+now[4]
    filestat_ctime=time.ctime(os.stat(picLocation+fd).st_ctime).split()#creat time
    filestat_ctime[3]=filestat_ctime[0]+filestat_ctime[1]+filestat_ctime[2]+filestat_ctime[4]
    if now[3]==filestat_ctime[3]:
       logging.info('file existed')
       exit()
#--------------------------------------------------get webpage and analyse it
try:
  page=urllib2.urlopen("http://cn.bing.com")
except HTTPError, e:
  logging.info("The server couldn\'t fulfill the request.")
  logging.info("Error code: "+e.code)
except URLError, e:
  logging.info("We failed to reach a server.")
  logging.info("Reason: "+e.reason)

logging.info("got bing's index page")
pageBing=page.read()
pattern=re.compile(r"g_img={url:\'.*?\'")
urlAddresses=pattern.findall(pageBing)
#--------------------------------------------------constructing the desired url and path which will be used to store the image
urlAdd=urlAddresses[0].split("\'")[1]
wpName=picLocation+urlAdd.split(r"%")[-1]
#--------------------------------------------------get the image
urllib.urlretrieve(urlAdd,wpName)
logging.info("got the photo")
#--------------------------------------------------use pcmanfm to change wallpaper
cmd4chgwp="/usr/bin/pcmanfm --set-wallpaper=\""+wpName+"\""
os.system(cmd4chgwp)
logging.info('setting done=============================!!!')
